package com.example.forwardmessages

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

/**
 * Helper class for managing app notifications, including error notifications
 * that persist even when the app fails.
 */
class NotificationHelper(private val context: Context) {
    private val errorLogger: ErrorLogger = ErrorLogger(context)
    private val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(context)
    
    companion object {
        private const val ERROR_CHANNEL_ID = "app_error_channel"
        private const val ERROR_CHANNEL_NAME = "应用错误通知"
        private const val ERROR_CHANNEL_DESCRIPTION = "显示应用程序错误和失败信息"
        private const val ERROR_NOTIFICATION_ID = 1001
        
        private const val INFO_CHANNEL_ID = "app_info_channel"
        private const val INFO_CHANNEL_NAME = "应用信息通知"
        private const val INFO_CHANNEL_DESCRIPTION = "显示应用程序信息和操作反馈"
        private const val INFO_NOTIFICATION_ID = 1002
    }

    init {
        createNotificationChannels()
    }

    /**
     * Create notification channels required for Android Oreo and above
     */
    @SuppressLint("NewApi")
    private fun createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val errorChannel = NotificationChannel(
                ERROR_CHANNEL_ID,
                ERROR_CHANNEL_NAME,
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = ERROR_CHANNEL_DESCRIPTION
                setShowBadge(true)
            }
            
            val infoChannel = NotificationChannel(
                INFO_CHANNEL_ID,
                INFO_CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = INFO_CHANNEL_DESCRIPTION
                setShowBadge(true)
            }

            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(errorChannel)
            notificationManager.createNotificationChannel(infoChannel)
        }
    }

    /**
     * Show an error notification and log the error to persistent storage
     */
    fun showErrorNotification(source: String, message: String, exception: Exception? = null) {
        // Log the error to persistent storage first
        errorLogger.logError(source, message, exception)
        
        // Create intent to launch the main activity when notification is tapped
        val intent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            } else {
                PendingIntent.FLAG_UPDATE_CURRENT
            }
        )

        // Build the notification
        val notification = NotificationCompat.Builder(context, ERROR_CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_alert)
            .setContentTitle("应用错误 ($source)")
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        // Show the notification
        with(notificationManager) {
            notify(ERROR_NOTIFICATION_ID, notification)
        }
    }

    /**
     * 显示信息通知，用于提供操作反馈或应用状态更新
     */
    fun showInfoNotification(title: String, message: String) {
        // Create intent to launch the main activity when notification is tapped
        val intent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            } else {
                PendingIntent.FLAG_UPDATE_CURRENT
            }
        )

        // Build the notification
        val notification = NotificationCompat.Builder(context, INFO_CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        // Show the notification
        with(notificationManager) {
            notify(INFO_NOTIFICATION_ID, notification)
        }
    }
    
    /**
     * Get the error logger instance
     */
    fun getErrorLogger(): ErrorLogger {
        return errorLogger
    }
}